const { net} = require('electron')
const Base64 = require('js-base64').Base64;
const urlparse = require('url');
const http = require('http');
const https = require('https');
const axios = require('axios');

function sendNetRequest(requestUrl, method, headers, params, callback) {
    // const parsedUrl = urlparse.parse(url);
    // const options = {
    //     method: 'GET',
    //     url:url
    // };
    const request = net.request({method: method, url: requestUrl});
    // const request = net.request(requestUrl);
    Object.entries(headers).forEach(([name, value]) => {
        if (name == 'token' || name == 'Cookie' || name.startsWith('Accept') || name == 'User-Agent' || name == 'Referer' || name == 'Content-Type') {
            request.setHeader(name, value);

        }
    });
    //   request.setHeader("Content-Type","application/json;charset=UTF-8");
    if (params) {
        request.write(params);
    }
    request.on('response', (response) => {
        // console.log(`STATUS: ${response.statusCode}`)
        // console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
        let resultData = []
        response.on('data', (chunk) => {
            resultData.push(chunk);
            // console.log(res);
        });
        response.on('end', () => {
            var res = null;
            // try{
            //     res = JSON.parse(resultData);
            // }catch(e){
            //     var str = resultData.map(buffer => buffer.toString()).join('');
            //     var replacedStr = str.replace(/,]/g, ']').replace(/,}/g, '}')
            //     res = JSON.parse(replacedStr);
            // }
            // var jsonObj = {'aweme_list':[]};
            // var jsonRes = res;
            // for(var i = 0;i < jsonRes['aweme_list'].length; i++){
            //     var node = jsonRes['aweme_list'][i];
            //     jsonObj['aweme_list'].push({'aweme_id':node['aweme_id']});
            // }
            // jsonRes['aweme_list'];

            // callback({success:true,data:JSON.stringify(jsonObj)});
            try {
                var str = resultData.map(buffer => buffer.toString()).join('');
                res = str.replace(/,]/g, ']').replace(/,}/g, '}');
            } catch (e) {
                console.error(e);
            }
            callback({success: true, data: res});
            // console.log('response data'+res);
        })
    })
    // 请求错误事件
    request.on('error', (error) => {
        console.error('请求出错:', error);
        callback({data: JSON.stringify({success: false, data: error})});
    });
    request.end();
}

function promiseRequest(options){
    let url = options.url;
    let method = options.method;
    let headers = options.headers || {};
    if(method.toLowerCase() == 'get'){
        return getPromiseRequest(url,headers);
    }else{
        let data = options.data;
        return postPromiseRequest(url,data,headers);
    }
}

//不能redirect for 301,302 用于基础http/https请求
function getPromiseRequest(url, headers) {
    if (!headers) {
        // headers = {
        //     'Content-Type': 'application/json',
        //     'Content-Length': Buffer.byteLength(data)
        // }
        headers = {}
    }
    const protocol = url.startsWith('https') ? https : http;
    const parsedUrl = urlparse.parse(url);
    const options = {
        method: 'GET',
        protocol: parsedUrl.protocol,
        hostname: parsedUrl.hostname,
        port: parsedUrl.port,
        path: parsedUrl.path,
        headers: headers
    };
    return new Promise((resolve, reject) => {
        protocol.get(options, (response) => {
            let chunks_of_data = [];

            response.on('data', (fragments) => {
                chunks_of_data.push(fragments);
            });

            response.on('end', () => {
                let response_body = Buffer.concat(chunks_of_data);
                resolve(response_body.toString());
            });

            response.on('error', (error) => {
                reject(error);
            });
        });
    });
}

function postPromiseRequest(url, data,headers) {
    if (!headers) {
        headers = {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(data)
        }
    }
    const protocol = url.startsWith('https') ? https : http;
    const parsedUrl = urlparse.parse(url);
    const options = {
        method: 'POST',
        protocol: parsedUrl.protocol,
        hostname: parsedUrl.hostname,
        port: parsedUrl.port,
        path: parsedUrl.path,
        headers: headers
    };
    return new Promise((resolve, reject) => {
        // const options = {
        //     hostname: 'www.example.com',
        //     port: 80,
        //     path: '/endpoint',
        //     method: 'POST',
        //     headers: {
        //         'Content-Type': 'application/json',
        //         'Content-Length': Buffer.byteLength(data),
        //     },
        // };
        let req = protocol.request(options, (response) => {
            let chunks_of_data = [];

            response.on('data', (fragments) => {
                chunks_of_data.push(fragments);
            });

            response.on('end', () => {
                let response_body = Buffer.concat(chunks_of_data);
                resolve(response_body.toString());
            });

            response.on('error', (error) => {
                reject(error);
            });
        });

        // 发送请求体数据
        if(data){
            req.write(data);
        }
        req.end();

    });
}

function request(options){
    let url = options.url;
    let method = options.method;
    let headers = options.headers || {};
    if(method.toLowerCase() == 'get'){
        let params = options.params || {};
        return axios.get(url, {
            params: params,
            headers: headers
        });
    }else{
        let data = options.data;
        return axios.post(url, data, {
            headers: headers
        });
    }

}

// 导出模块函数
module.exports = {
    sendNetRequest,
    getPromiseRequest,
    postPromiseRequest,
    promiseRequest,
    request,

};

